package com.sita.cfmoto.drivedata;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.malinskiy.superrecyclerview.OnMoreListener;
import com.malinskiy.superrecyclerview.SuperRecyclerView;
import com.rohit.recycleritemclicksupport.RecyclerItemClickSupport;
import com.sita.cfmoto.R;
import com.sita.cfmoto.drivedata.rest.DriveDataBean;
import com.sita.cfmoto.event.HasBindVehicleEvent;
import com.sita.cfmoto.rest.model.response.FetchVehicleDriveHistoryResponse;
import com.sita.cfmoto.utils.LocalStorage;
import com.sita.cfmoto.utils.TracksInfoUtils;
import com.sita.cfmoto.utils.VehicleUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;

public class DriveDataHistoryFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, OnMoreListener {

    private final String TAG = DriveDataHistoryFragment.class.getSimpleName();

    @Bind(R.id.drive_data_list)
    SuperRecyclerView listView;
    @Bind(R.id.no_history_text)
    TextView noHistoryTextView;

    private DriveDataHistoryAdapter mAdapter;
    private LinearLayoutManager mLinearLayoutManager;
    private int currPage = 0;
    private boolean isRequesting = false;
    private boolean isAskMore = false;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.content_drive_data_history, null);
        ButterKnife.bind(this, view);

        mLinearLayoutManager = new LinearLayoutManager(getContext());
        listView.setLayoutManager(mLinearLayoutManager);

        mAdapter = new DriveDataHistoryAdapter();
        mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
            @Override
            public void onChanged() {
                if (mAdapter.getItemCount() == 0) {
                    noHistoryTextView.setVisibility(View.VISIBLE);
                    listView.setVisibility(View.INVISIBLE);
                }else {
                    noHistoryTextView.setVisibility(View.GONE);
                    listView.setVisibility(View.VISIBLE);
                }
            }
        });
        listView.setAdapter(mAdapter);
//        mAdapter.setData(DriveDataUtils.INSTANCE.getDriveDataList());

        listView.setOnMoreListener(this);
        listView.setRefreshListener(this);

        final Context context = getContext();

        RecyclerItemClickSupport.addTo(listView.getRecyclerView())
                .setOnItemClickListener(new RecyclerItemClickSupport.OnItemClickListener() {
                    @Override
                    public void onItemClicked(RecyclerView recyclerView, int position, View v) {
                        DriveDataConstants.driveData = mAdapter.getItem(position);
                        Intent intent = new Intent(context, DriveDataHistoryDetailActivity.class);
                        context.startActivity(intent);
                    }
                });

        if (!LocalStorage.hasBindVehicle()) {
            noHistoryTextView.setVisibility(View.VISIBLE);
            listView.setVisibility(View.INVISIBLE);
        }
        initListView();

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    public void onEventMainThread(HasBindVehicleEvent event) {
        if (event.hasBindVehicle) {
            onRefresh();
        }else {
            noHistoryTextView.setVisibility(View.VISIBLE);
            listView.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public void onMoreAsked(int overallItemsCount, int itemsBeforeMore, int maxLastVisiblePosition) {
        if (!LocalStorage.hasBindVehicle()) return;
        if (isRequesting) return;
        isAskMore = true;
        currPage += 1;
        fetchHistory();
//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                listView.setLoadingMore(false);
//            }
//        }, 1000);
    }

    @Override
    public void onRefresh() {
        if (!LocalStorage.hasBindVehicle()) return;
        if (isRequesting) return;
        isAskMore = false;
        currPage = 0;
        fetchHistory();
//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                listView.setRefreshing(false);
//                mLinearLayoutManager.scrollToPosition(0);
//            }
//        }, 1000);
    }

    private void initListView() {
        if (mAdapter.getItemCount() <= 0) {
            // do ask more
            onRefresh();
        }
    }

    private void fetchHistory() {
        isRequesting = true;
        VehicleUtils.fetchVehicleDriveHistoryState(new VehicleUtils.FetchVehicleDriveHistoryListener() {
            @Override
            public void onSuccess(List<FetchVehicleDriveHistoryResponse> list) {
                isRequesting = false;
                if (list == null && isAskMore == true) {
                    // ask more 失败，则重新请求当前页
                    currPage -= 1;
                } else {
                    extractData(list);
                }
            }
        }, currPage);
    }

    private void extractData(List<FetchVehicleDriveHistoryResponse> list) {
        if (list == null) {
            return;
        }

        List<DriveDataBean> data = new ArrayList<>();
        for (FetchVehicleDriveHistoryResponse response:
             list) {
            DriveDataBean bean = new DriveDataBean();
            bean.serverId =Long.parseLong( response.routeId);
            bean.begintime = response.begintime;
            bean.endtime = response.endtime;
            bean.distance = response.distance;
            bean.speed = response.speed;
            bean.routefile =  response.routefile;
            bean.soc = response.oilWear;

            // save data into database
            TracksInfoUtils.saveRouteIntoDbWithoutPoints(bean);
            // after save data into database, bean has id saved
            data.add(bean);
        }
        if (data!=null && data.size() > 0) {
            if(isAskMore) {
                mAdapter.appendData(data);
            }else {
                mAdapter.setData(data);
            }
            mAdapter.notifyDataSetChanged();
        }

    }


}
